﻿

namespace KingerRobot.MexicoSailunMDC.SpiService;

public class BMonitorManage : IMonitorManage
{
    public CuringListBeans GetCuringNodesByEquipId(long equipId)
    {
        CuringListBeans result = new();
        var db = Db.Default;

        var allCuringNoOrders = GetAllCuringNoOrder();
        var allCuringOrders = GetAllCuringHaveOrder();

        var seBox = db.ScadaBoxs.Where(t => t.EquipId == equipId).FirstOrDefault();
        if (seBox is null)
        {
            return result;
        }

        var curingNoOrders = allCuringNoOrders.Where(t => t.CuringCode == seBox.BoxCode).ToList();
        var curingOrders = allCuringOrders.Where(t => t.CuringCode == seBox.BoxCode).ToList();

        result = GetCuringDetails(seBox, curingNoOrders, curingOrders);

        //result.CuringDetails


        return result;
    }

    public static List<CuringMessageBeans> GetAllCuringNoOrder()
    {
        var db = Db.Default;
        var query = db.RcsEquipCurings
            .GroupJoin(db.WcsTasks, f => f.LocId, s => s.TargetLoc, (f, s) => new
            {

                f.Id,
                f.CuringCode,
                f.UseFlag,
                TargetLoc = f.LocId,
                Task = s,
                f.CuringDir,
            })
        .SelectMany(f => f.Task.DefaultIfEmpty(), (f, s) => new
        {
            f.Id,
            f.CuringCode,
            f.UseFlag,
            s.TaskNo,
            f.TargetLoc,
            f.CuringDir,
        }).GroupJoin(db.WmsOutOrderSummarys, f => f.TargetLoc, s => s.TargetLoc, (f, s) => new
        {
            f.CuringDir,
            f.Id,
            f.CuringCode,
            f.UseFlag,
            f.TaskNo,
            Summary = s,
        })
        .SelectMany(f => f.Summary.DefaultIfEmpty(), (f, s) => new
        {
            Id = f.Id,
            TaskNo = f.TaskNo,
            CuringCode = f.CuringCode,
            UseFlag = f.UseFlag,
            LeftRightFlag = f.CuringDir,
            Summary = s
        }).Where(t => t.Summary == null).Select(f => new CuringMessageBeans
        {
            Id = f.Id,
            TaskNo = f.TaskNo,
            CuringCode = f.CuringCode,
            UseFlag = f.UseFlag,
            LeftRightFlag = f.LeftRightFlag,
            //SummaryId = f.Summary.Id ?? 0,
            //SummaryReamrk = f.Summary.RemarkMemo,
            //CmdTime = f.Summary.CreateTime,
        }).OrderBy(f => f.CuringCode).ToList();

        return query;
    }
    public static List<CuringMessageBeans> GetAllCuringHaveOrder()
    {
        var db = Db.Default;
        var query = db.RcsEquipCurings
            .GroupJoin(db.WcsTasks, f => f.LocId, s => s.TargetLoc, (f, s) => new
            {
                f.Id,
                f.CuringCode,
                f.UseFlag,
                TargetLoc = f.LocId,
                Task = s,
                f.CuringDir,
            })
        .SelectMany(f => f.Task.DefaultIfEmpty(), (f, s) => new
        {
            f.Id,
            f.CuringCode,
            f.UseFlag,
            s.TaskNo,
            s.SkuId,
            CmdTime = s.CreateTime,
            f.TargetLoc,
            f.CuringDir,
        }).GroupJoin(db.ProdSkus, f => f.SkuId, s => s.Id, (f, s) => new
        {

            f.Id,
            f.CuringCode,
            f.UseFlag,
            f.TaskNo,
            f.SkuId,
            f.CmdTime,
            f.TargetLoc,
            f.CuringDir,
            ProdSku = s,
        })
        .SelectMany(f => f.ProdSku.DefaultIfEmpty(), (f, s) => new
        {

            f.Id,
            f.CuringCode,
            f.UseFlag,
            f.TaskNo,
            f.CmdTime,
            f.TargetLoc,
            f.CuringDir,
            s.SkuCode,
        })

        //.Join(db.WcsTaskCmds, f => f.TaskNo, s => s.TaskNo, (f, s) => new
        //{

        //    f.Id,
        //    f.CuringCode,
        //    f.UseFlag,
        //    f.TaskNo,
        //    f.TargetLoc,
        //    f.CuringDir,
        //    CmdTime = s.CreateTime,
        //})
         .GroupJoin(db.WmsOutOrderSummarys, f => f.TargetLoc, s => s.TargetLoc, (f, s) => new
         {
             f.CuringDir,
             f.Id,
             f.CuringCode,
             f.UseFlag,
             f.TaskNo,
             f.CmdTime,
             f.SkuCode,
             Summary = s,
         })
        .SelectMany(f => f.Summary.DefaultIfEmpty(), (f, s) => new
        {
            Id = f.Id,
            TaskNo = f.TaskNo,
            CuringCode = f.CuringCode,
            UseFlag = f.UseFlag,
            LeftRightFlag = f.CuringDir,
            Summary = s,
            SkuCode = f.SkuCode,
        }).Where(t => t.Summary != null).Select(f => new CuringMessageBeans
        {
            Id = f.Id,
            TaskNo = f.TaskNo,
            CuringCode = f.CuringCode,
            UseFlag = f.UseFlag,
            LeftRightFlag = f.LeftRightFlag,
            SummaryId = f.Summary.Id ?? 0,
            SummaryReamrk = f.Summary.RemarkMemo,
            CmdTime = f.Summary.CreateTime,
            SkuCode = f.SkuCode,
        }).OrderBy(f => f.CuringCode).ToList();

        return query;
    }


    private CuringListBeans GetCuringDetails(POScadaBox seBox, List<CuringMessageBeans> curingNoOrders, List<CuringMessageBeans> curingOrders)
    {


        CuringListBeans result = new();
        List<CuringDetailsBeans> curingDetailsList = new();

        CuringDetailsBeans curingDetailsL = new();
        CuringDetailsBeans curingDetailsR = new();
        curingDetailsL.CuringMode = "左L";
        curingDetailsR.CuringMode = "右R";

        //WriteLog($"curingNoOrder详情{curingNoOrders.ToJson()}", true);
        //WriteLog($"curingOrders详情{curingOrders.ToJson()}", true);
        //WriteLog($"seBox{seBox.ToJson()}", true);

        //if (!String.IsNullOrWhiteSpace(result))

        //{
        //    result = result + $"<br>设备编号：{param?.BoxCode}" + $"<br>设备名：{param.ShowName}";
        //}
        //else
        //{
        // result = result + $"设备名：{param.ShowName}<br>";
        //}

        //var curingCode = seBox.ShowCode;
        var materialCode = seBox.TcmSpec;
        var materialName = seBox.TcmSpecDesc;
        var curingTime = seBox.RegDt;
        result.CuringCode = seBox.ShowName;


        var stocks = GetStockByMaterialCode(materialCode);

        var stockCount = stocks.Where(t => t.TireLock == 0 && t.TbmExpirationTime >= DateTime.Now).Count();
        var timeOutCount = stocks.Where(t => t.TireLock == 0 && t.TbmExpirationTime < DateTime.Now).Count();
        var lockCount = stocks.Where(t => t.TireLock == 1).Count();
        var experimentCount = 0;


        var orderCount = 0;
        var taskCount = 0;
        var planCount = 0;



        //判断是否有订单(没有订单)
        if (curingNoOrders.Count > 0)
        {
            if (curingNoOrders.Count >= 2)
            {
                //if (!String.IsNullOrWhiteSpace(result))
                //{
                //    result = result + "<br>";
                //}
                result.Remark = "订单状态：未生成订单";
                orderCount = 0;

                if (seBox.RcvFlag == "Y")
                {
                    planCount = 2;
                    curingDetailsL.MaterialCode = materialCode;
                    curingDetailsL.MaterialName = materialName;
                    curingDetailsR.MaterialCode = materialCode;
                    curingDetailsR.MaterialName = materialName;
                }
                else
                {
                    planCount = 0;
                    stockCount = 0;
                    timeOutCount = 0;
                    lockCount = 0;
                    curingTime = null;
                }
            }
            else
            {
                var curingNoOrderL = curingNoOrders.Where(t => t.LeftRightFlag == "L").FirstOrDefault();
                if (curingNoOrderL is not null)
                {

                    result.Remark = $"订单状态：L：未生成订单，R：已生成订单";
                    orderCount = 1;
                }
                else
                {

                    result.Remark = $"订单状态：L：已生成订单，R：未生成订单";
                    orderCount = 1;
                }

            }
            //var curingNoOrders.Where(t => t.LeftRightFlag == "L").FirstOrDefault();
        }
        else
        {
            //判断任务
            var curingtaskOrders = curingOrders.Where(t => t.TaskNo > 0).ToList();
            var curingtaskOrderL = curingtaskOrders.Where(t => t.LeftRightFlag == "L").FirstOrDefault();
            var curingtaskOrderR = curingtaskOrders.Where(t => t.LeftRightFlag == "R").FirstOrDefault();

            if (curingtaskOrders is not null && curingtaskOrders.Count > 0)
            {
                planCount = 2;
                orderCount = 2;
                result.Remark = $"规格{materialCode}已经创建订单";

                if (curingtaskOrderL is not null)
                {
                    curingDetailsL.TaskNo = curingtaskOrderL.TaskNo;
                    curingDetailsL.ProductCode = curingtaskOrderL.SkuCode;

                    taskCount += 1;
                    //result.Remark += $"L - 任务号：{curingtaskOrderL.TaskNo}  ,  L - 条码：{curingtaskOrderL.SkuCode} ";
                }
                else
                {
                    curingDetailsL.TaskNo = 0;
                    curingDetailsL.ProductCode = "";
                    //result.Remark = $"L - 未创建";
                }



                if (curingtaskOrderR is not null)
                {
                    curingDetailsR.TaskNo = curingtaskOrderR.TaskNo;
                    curingDetailsR.ProductCode = curingtaskOrderR.SkuCode;
                    taskCount += 1;
                    //result.Remark += "R - 任务号：{curingtaskOrderL.TaskNo}  ,  L - 条码：{curingtaskOrderL.SkuCode}";
                }
                else
                {
                    curingDetailsR.TaskNo = 0;
                    curingDetailsR.ProductCode = "";
                    //result.Remark +=  "R - 未创建任务 ";
                }

            }
            else
            {
                planCount = 2;
                curingDetailsL.TaskNo = 0;
                curingDetailsL.ProductCode = "";
                curingDetailsR.TaskNo = 0;
                curingDetailsR.ProductCode = "";

                //result = result + "L-任务号：未创建 ，L-条码：未创建<br>";
                //result = result + "R-任务号：未创建 ，R-条码：未创建<br>";

                var curingOrderL = curingOrders.Where(t => t.LeftRightFlag == "L").FirstOrDefault();
                var curingOrderR = curingOrders.Where(t => t.LeftRightFlag == "R").FirstOrDefault();
                if (curingOrderL is not null)
                {
                    result.Remark += $"L-无订单原因：{curingOrderL.SummaryReamrk} ";
                    //result = result + "L-无订单原因：" + curingOrderL.SummaryReamrk + "<br>";
                }
                if (curingOrderR is not null)
                {
                    result.Remark += $"R-无订单原因：{curingOrderR.SummaryReamrk} ";
                    //result = result + "R-无订单原因：" + curingOrderR.SummaryReamrk + "<br>";
                }

            }




            //var materialName = "";
            if (!string.IsNullOrWhiteSpace(materialCode))
            {
                //var material = _ProdMaterial.GetMaterialByCode(materialCode);
                //materialName = material?.MaterialName ?? "";

                curingDetailsL.MaterialCode = materialCode;
                curingDetailsR.MaterialCode = materialCode;

                curingDetailsL.MaterialName = materialName;
                curingDetailsR.MaterialName = materialName;


            }
            else
            {
                materialName = $"硫化物料：MES未传递硫化物料";

                curingDetailsL.MaterialName = materialName;
                curingDetailsR.MaterialName = materialName;
            }

        }
        curingDetailsList.Add(curingDetailsL);
        curingDetailsList.Add(curingDetailsR);
        result.CuringDetails = curingDetailsList;
        result.PlanCount = planCount;
        result.OrderCount = orderCount;
        result.TaskCount = taskCount;
        result.ExperimentCount = 0;
        result.StockCount = stockCount;
        result.TimeOutCount = timeOutCount;
        result.LockCount = lockCount;
        result.ExperimentCount = experimentCount;
        result.CuringTime = curingTime;


        //WriteLog($"硫化机详情{result.ToJson()}", true);
        return result;
    }

    public List<StockBeans> GetStockByMaterialCode(string materialCode)
    {
        var db = Db.Default;
        List<StockBeans> result = new();
        result = db.WcsLocSkus.Join(db.RcsLocations, f => f.LocId, s => s.Id, (f, s) => new
        {
            f.SkuId,
            s.LocType,
            s.LocEnable,
            s.InEnable,
            s.OutEnable,
        }).Where(t => t.LocEnable == 1 && t.InEnable == 1 && t.OutEnable == 1)
        .Join(db.ProdSkuProducts, f => f.SkuId, s => s.SkuId, (f, s) => new
        {
            f.LocType,
            s.ProductId,
        }).Join(db.ProdProducts, f => f.ProductId, s => s.Id, (f, s) => new
        {
            f.LocType,
            f.ProductId,
            s.ProductCode,
            s.MaterialId,
            s.TireLock,
            s.TbmExpirationTime,
        }).Join(db.ProdMaterials, f => f.MaterialId, s => s.Id, (f, s) => new
        {
            f.LocType,
            f.ProductCode,
            f.MaterialId,
            f.TireLock,
            f.TbmExpirationTime,
            s.MaterialCode,
        }).Where(t => t.MaterialCode == materialCode && t.LocType == (int)EnumLocType.Location)
        .Select(t => new StockBeans
        {
            MaterialCode = t.MaterialCode,
            MaterialId = t.MaterialId,
            TireLock = t.TireLock,
            ProductCode = t.ProductCode,
            TbmExpirationTime = t.TbmExpirationTime,
        }).ToList();

        return result;
    }

}
    /// <summary>
    /// 硫化机排返回beans
    /// </summary>
    public class CuringMessageBeans
    {
        /// <summary>
        /// 唯一Id
        /// </summary>
        public long? Id { get; set; }

        /// <summary>
        /// 任务号
        /// </summary>
        public int? TaskNo { get; set; }

        /// <summary>
        ///  是否可用
        /// </summary>
        public int? UseFlag { get; set; }

        /// <summary>
        /// 左右膜标识
        /// </summary>
        public string LeftRightFlag { get; set; }

        /// <summary>
        /// 硫化机编号
        /// </summary>
        public string CuringCode { get; set; }

        /// <summary>
        /// 鼠标悬停结果
        /// </summary>
        public string MouseOverResult { get; set; }

        /// <summary>
        /// 颜色
        /// </summary>
        public string Color { get; set; }
        /// <summary>
        /// 1:(1号右模；2号左模)；2:(1号左模；2号右模)
        /// </summary>
        public int Signs { get; set; }
        /// <summary>
        /// 1:(1号右模；2号左模)；2:(1号左模；2号右模)
        /// </summary>
        public int Index { get; set; }

        public long? SummaryId { get; set; }
        public DateTime? CmdTime { get; set; }
        public string SummaryReamrk { get; set; }

        public string SkuCode { get; set; }

        public string MaterialCode { get; set; }
        public string MaterialName { get; set; }


    }
    public class StockBeans
    {
        public string ProductCode { get; set; }
        public string MaterialCode { get; set; }

        public long? MaterialId { get; set; }
        public int? TireLock { get; set; }
        public DateTime? TbmExpirationTime { get; set; }

    }


